package com.example.netty.protocoltcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;

public class MyServerhandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private AtomicInteger i = new AtomicInteger(0);
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
        // 接收到数据并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务端接收到信息如下");
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, CharsetUtil.UTF_8));

        System.out.println("服务器接收到消息包数量：" + i.incrementAndGet());
        // 服务端回复消息
        MessageProtocol msg1 = new MessageProtocol();
        String msgg = "收到消息了，死鬼";
        msg1.setLen(msgg.getBytes().length);
        msg1.setContent(msgg.getBytes());
        ctx.writeAndFlush(msg1);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
